package servlet;


import entity.Animal;
import entity.AnimalCategory;
import service.AnimalCategoryService;
import service.AnimalService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

@WebServlet("/addAnimal")
public class AddAnimalServlet extends HttpServlet {
    private AnimalService animalService;
    private AnimalCategoryService animalCategoryService ;


    @Override
    public void init() throws ServletException {
        animalService = new AnimalService();
        animalCategoryService = new AnimalCategoryService();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String birthdateStr = request.getParameter("birthdate");
        String description = request.getParameter("description");
        int categoryId = Integer.parseInt(request.getParameter("categoryId"));

        Timestamp birthdate = Timestamp.valueOf(birthdateStr);

        Animal animal = new Animal();
        animal.setName(name);
        animal.setBirthdate(birthdate);
        animal.setDescription(description);
        animal.setCategoryId(categoryId);

        boolean result = animalService.addAnimal(animal);
        System.out.println(result);
        if (result) {
            // 查询所有动物分类
            List<AnimalCategory> categories = animalCategoryService.getAllAnimalCategories();
            request.setAttribute("categories", categories);
            List<Animal> animals = animalService.getAllAnimals();
            request.setAttribute("animals", animals);
            request.getRequestDispatcher("/adminIndex.jsp").forward(request, response);
        } else {
            request.setAttribute("errorMessage", "添加动物失败");
            request.getRequestDispatcher("/adminIndex.jsp").forward(request, response);
        }
    }
}
